package com.yakaten.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

import org.seasar.framework.util.ResourceUtil;

import com.yakaten.dto.YahooItemInfoDto;
import com.yakaten.exception.YahooException;

public class YahooItemService {

	protected static final String REGEX_GENRE_DIV = "<div id=\"TopSPathList1\">(.+?)</div>";
	protected static final Pattern PATTERN_GENRE_DIV  = Pattern.compile(
			REGEX_GENRE_DIV, Pattern.MULTILINE);

	protected static final String REGEX_GENRE_NAME_LI = "<li><a.+?>(.+?)</a>.+?</li>";
	protected static final Pattern PATTERN_GENRE_NAME_LI  = Pattern.compile(
			REGEX_GENRE_NAME_LI, Pattern.MULTILINE);

	protected static final String REGEX_ITEM_NAME_LI = "<li><strong>(.+?)</strong></li>";
	protected static final Pattern PATTERN_ITEM_NAME_LI  = Pattern.compile(
			REGEX_ITEM_NAME_LI, Pattern.MULTILINE);

	protected static final String REGEX_ITEM_PRICE = "<span property=\"product:salePrice\">(.+?)</span>.+?</span>";
	protected static final Pattern PATTERN_ITEM_PRICE  = Pattern.compile(
			REGEX_ITEM_PRICE, Pattern.MULTILINE);

	protected static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###.###");

	public YahooItemInfoDto getItemInfo(String itemId) throws YahooException{
		YahooItemInfoDto itemInfoDto = new YahooItemInfoDto();
		itemInfoDto.setItemId(itemId);

		String YAHOO_SHOPPING_HOST = ResourceUtil.getProperties("yakaten.properties").getProperty("yahoo.shopping.host");
		String YAHOO_STORE_URL = ResourceUtil.getProperties("yakaten.properties").getProperty("yahoo.store.url");
		String YAHOO_PAGE_EXT = ResourceUtil.getProperties("yakaten.properties").getProperty("yahoo.page.ext");

		String URL = YAHOO_SHOPPING_HOST.concat(YAHOO_STORE_URL).concat(itemId).concat(YAHOO_PAGE_EXT);

		HttpURLConnection connection = null;
		BufferedReader bufferedReader = null;

		try {
			URL itemPageUrl = new URL(URL);
			connection = (HttpURLConnection) itemPageUrl.openConnection();
			connection.setRequestProperty("Accept-Encoding","gzip,deflate");

			connection.connect();

			boolean usingGZIP = false;

			List<String> contentEncodings = connection.getHeaderFields().get( "Content-Encoding" );
			if ( contentEncodings != null ) {
				for ( int i = 0; i < contentEncodings.size(); ++i ) {
					String contentEncoding = contentEncodings.get( i );
					if ( contentEncoding.equals( "gzip" ) ) {
						usingGZIP = true;
						break;
					}
				}
			}

			InputStream urlStream = connection.getInputStream();
			if ( usingGZIP ) {
				bufferedReader = new BufferedReader(new InputStreamReader(new GZIPInputStream( urlStream ), "EUC-JP"));;
			} else {
				bufferedReader = new BufferedReader(new InputStreamReader(urlStream, "EUC-JP"));
			}

			String ss = null;
			StringBuffer htmlBuffer = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				htmlBuffer.append(ss);
			}

			//genre
			if (htmlBuffer != null) {

				Matcher matcherGenreDiv = PATTERN_GENRE_DIV.matcher(htmlBuffer);
				if (matcherGenreDiv.find()) {
					String genreLi = matcherGenreDiv.group(1);
					//genre
					Matcher matcherGenreNameLi = PATTERN_GENRE_NAME_LI.matcher(genreLi);
					String genreList = "";
					int i=0;
					while (matcherGenreNameLi.find()) {
						if(i++!=0){
							String genreName = matcherGenreNameLi.group(1);
							genreList+=":"+genreName;
						}
					}
					if(genreList.length()>0&&genreList.startsWith(":")){
						genreList=genreList.substring(1);
					}
					itemInfoDto.setItemGenre(genreList);

					//itemName
					Matcher matcherItemName = PATTERN_ITEM_NAME_LI.matcher(htmlBuffer);
					String itemName ="";
					if (matcherItemName.find()) {
						itemName =matcherItemName.group(1);
					}
					itemInfoDto.setItemName(itemName);
				}

				//price
				Matcher matcherItemPrice = PATTERN_ITEM_PRICE.matcher(htmlBuffer);
				if (matcherItemPrice.find()) {
					String price = matcherItemPrice.group(1);
					try {
						itemInfoDto.setItemPrice(PRICE_FORMAT.parse(price).longValue());
					} catch (ParseException e) {

					}
				}



			}

		} catch (MalformedURLException e) {
			throw new YahooException(e);
		} catch (IOException e) {
			throw new YahooException(e);
		}finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				connection.disconnect();
			}

//			if (out != null) {
//				try {
//					out.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
		}

		return itemInfoDto;
	}
	public static void main(String [] args){

//		System.getProperties().put("proxySet", "true");
//
//		System.getProperties().put("proxyPort", "80");
//
//		System.getProperties().put("proxyHost", "proxysv");

		try {
			System.out.println(new YahooItemService().getItemInfo("4905524892901--"));
		} catch (YahooException e) {
			e.printStackTrace();
		};

	}

}
